package com.orcsystem.product.exception;

import com.orcsystem.common.exception.BizCodeEnume;
import com.orcsystem.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.orcsystem.product.controller")  // 这个包下的异常 统一进行处理
@RestControllerAdvice(basePackages = "com.orcsystem.product.controller")
public class OrcExceptionControllerAdvice {

    /**
     * 处理校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)  //指定 可以处理那些类型的异常
    public R handleVaildException(MethodArgumentNotValidException e){
            log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
        HashMap<Object, Object> errorMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();// 数据校验的结果
        bindingResult.getFieldErrors().forEach((feildError)->{
                    errorMap.put(feildError.getField(),feildError.getDefaultMessage());
                }
            );
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put(
                "data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class) // 处理任意 异常
    public R handleException(Throwable throwable){
        log.error("错误",throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
